<template>
  <div class="course-form-container">
    <el-container>
      <el-header class="form-header">
        <el-page-header @back="$router.go(-1)" :content="courseId ? '课程详情' : '创建课程'">
        </el-page-header>
      </el-header>
      <el-main class="form-main">
        <el-form :model="courseForm" :rules="rules" ref="courseFormRef" label-width="150px" style="width: 100%;">
          <el-form-item label="课程名称" prop="title">
            <el-input v-model="courseForm.title" placeholder="请输入课程名称"></el-input>
          </el-form-item>
          <el-form-item label="课程封面">
            <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false" :on-success="handleCoverSuccess" :before-upload="beforeCoverUpload">
              <img v-if="courseForm.coverUrl" :src="courseForm.coverUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="el-upload__tip">只能上传 jpg/png 文件，且不超过 2MB</div>
          </el-form-item>
          <el-form-item label="课程简介" prop="description">
            <el-input type="textarea" v-model="courseForm.description" :rows="4" placeholder="请输入课程简介"></el-input>
          </el-form-item>

          <el-button type="primary" size="small" @click="updateCourseInfo(courseId)">修改课程信息</el-button>

          <h3>章节管理</h3>
          <el-card class="chapter-card" v-for="(chapter, cIndex) in courseForm.chapters" :key="chapter.id || cIndex">
            <template #header>
              <div class="card-header">
                <span>章节 {{ cIndex + 1 }}：</span>
                <el-input v-model="chapter.title" placeholder="章节名称"
                  style="width: 200px; margin-right: 10px;"></el-input>
                <el-button type="primary" size="small"
                  @click="addOrUpdateChapterHandler(chapter.id,null)">修改章节</el-button>
                <el-button type="danger" size="small" @click="removeChapter(chapter.id)">删除章节</el-button>
              </div>
            </template>

            <h4>课时管理</h4>
            <el-table :data="chapter.lessons" style="width: 100%; margin-bottom: 10px;" border>
              <el-table-column type="index" label="序号" width="60"></el-table-column>
              <el-table-column label="课时名称" width="230">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.title" placeholder="课时名称"></el-input>
                </template>
              </el-table-column>

              <el-table-column prop="lessonType" header-align="center" align="center" label="课时类型" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.lessonType === 'video' ? 'primary' : 'success'">
                    {{ scope.row.lessonType === 'video' ? '视频' : (scope.row.lessonType === 'article' ? '图文' : '其他') }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="videoUrl" header-align="center" align="center" label="视频链接" width="175">
                <template slot-scope="scope">
                  <div style="display: flex; align-items: center; justify-content: center;">
                    <el-button v-if="scope.row.videoUrl" type="text" size="small"
                      @click="previewVideo(scope.row.videoUrl)" style="margin-right: 10px;">
                      点击查看
                    </el-button>
                    <span v-else style="margin-right: 10px;">无</span>

                    <el-button type="text" size="small" @click="openFileUploadDialog(scope.row.id, 'video')">
                      {{ scope.row.videoUrl ? '修改' : '上传' }}
                    </el-button>

                    <el-button v-if="scope.row.videoUrl" type="text" size="small"
                      @click="deleteVideoOrPdfUrl(scope.row.id, 'video', scope.row.videoUrl)">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="pdfUrl" header-align="center" align="center" label="PDF链接" width="175">
                <template slot-scope="scope">
                  <div style="display: flex; align-items: center; justify-content: center;">
                    <a v-if="scope.row.pdfUrl" :href="scope.row.pdfUrl" target="_blank"
                      style="margin-right: 10px;">点击查看</a>
                    <span v-else style="margin-right: 10px;">无</span>

                    <el-button type="text" size="small" @click="openFileUploadDialog(scope.row.id, 'pdf')">
                      {{ scope.row.pdfUrl ? '修改' : '上传' }}
                    </el-button>

                    <el-button v-if="scope.row.pdfUrl" type="text" size="small"
                      @click="deleteVideoOrPdfUrl(scope.row.id, 'pdf', scope.row.pdfUrl)">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="280">
                <template slot-scope="scope">
                  <div class="button-group"> <el-button type="primary" size="small"
                      @click="showAiKnowledgeBase(scope.row.id)">查看AI知识库</el-button>
                    <el-button type="primary" size="small"
                      @click="addOrUpdateLessonHandler(scope.row.id, null)">修改</el-button>
                    <el-button type="danger" size="small" @click="removeLesson(scope.row.id)">删除</el-button>
                  </div>
                </template>
              </el-table-column>

            </el-table>
            <el-button type="info" size="small" @click="addOrUpdateLessonHandler(null, chapter.id)">添加课时</el-button>
            <div class="right-actions" v-loading="generating" element-loading-text="生成中..."
              element-loading-spinner="el-icon-loading">
              <el-button type="primary" size="small" @click="showGenerateDialog(chapter.id,chapter.title)" :disabled="generating">
                生成 AI 文档
              </el-button>
              <el-button type="success" size="small" @click="generateTestPaper(chapter.id,chapter.title)" :disabled="generating">
                生成试卷
              </el-button>
            </div>
          </el-card>

          <el-button type="success" @click="addOrUpdateChapterHandler(null, courseId)"
            style="margin-top: 20px;">添加章节</el-button>

          <el-form-item class="form-actions">
            <el-button @click="$router.go(-1)">返回</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>

    <el-dialog title="选择生成文档类型" :visible.sync="generateDialogVisible" width="30%" center>
      <span>请选择您希望生成的文档类型：</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="generateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="generateAiFile(currentChapterId, 1,currentChapterTitle); generateDialogVisible = false">生成 Word
          (DOCX)</el-button>
        <el-button type="success" @click="generateAiFile(currentChapterId, 2,currentChapterTitle); generateDialogVisible = false">生成
          PDF</el-button>
      </span>
    </el-dialog>


    <el-dialog title="AI 知识库内容" :visible.sync="aiKnowledgeBaseVisible" width="60%" @close="aiKnowledgeBaseContent = ''">
      <div class="knowledge-base-viewer">
        <p v-html="aiKnowledgeBaseContent"></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="aiKnowledgeBaseVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <LessonUploadDialog ref="lessonUploadDialog" @uploaded="onFileUploaded" />

    <el-dialog title="视频预览" :visible.sync="previewVisible" width="60%" @close="previewVideoUrl = ''">
      <video v-if="previewVideoUrl" :src="previewVideoUrl" controls autoplay muted
        style="width: 100%; max-height: 500px;"></video>
    </el-dialog>

    <ChapterAddOrUpdate v-if="chapterAddOrUpdateFlag" ref="chapterAddOrUpdate" @refreshDataList="onRefreshDataList"
      @dialogClosed="onDialogClosed"></ChapterAddOrUpdate>

    <LessonAddOrUpdate v-if="lessonAddOrUpdateFlag" ref="lessonAddOrUpdate" @refreshDataList="onRefreshDataList"
      @dialogClosed="onDialogClosed"></LessonAddOrUpdate>

    <CourseAddOrUpdate v-if="courseAddOrUpdateFlag" ref="courseAddOrUpdate" @refreshDataList="onRefreshDataList"
      @dialogClosed="onDialogClosed"></CourseAddOrUpdate>
  </div>
</template>
<script>

import ChapterAddOrUpdate from "./components/chapter-add-or-update.vue"; 
import LessonUploadDialog from "./components/LessonUploadDialog.vue";
import LessonAddOrUpdate from "./components/lesson-add-or-update.vue"; 
import CourseAddOrUpdate from "./components/course-add-or-update.vue"; 

export default {
  title: 'CourseForm',
  data() {
    return {
      chapterAddOrUpdateFlag: false,
      lessonAddOrUpdateFlag:false,
      courseAddOrUpdateFlag:false,
      courseId: this.$route.query.id,
      generating: false,
      courseForm: {
        title: '',
        coverUrl: '',
        description: '',
        chapters: [],
      },
      previewVideoUrl: '',
      aiKnowledgeBaseVisible: false,
      aiKnowledgeBaseContent: '',  
      generateDialogVisible: false,
      currentChapterId: null,
      currentChapterTitle:null
    };
  },
    components: {
    ChapterAddOrUpdate,
    LessonUploadDialog,
    LessonAddOrUpdate,
    CourseAddOrUpdate
  },
  methods: {
    async fetchCourseDetails(id) {
      try {
        const token = localStorage.getItem('frontToken');
        const headers = { Token: token };

        const courseRes = await this.$http.get(`course/detail/${id}`, { headers });
        if (courseRes.data.code !== 0) {
          this.$message.error('课程信息获取失败');
          return;
        }

        const courseData = courseRes.data.data;
        this.courseForm.title = courseData.title;
        this.courseForm.coverUrl = courseData.coverImageUrl;
        this.courseForm.description = courseData.description;

        const chapterRes = await this.$http.get('chapter/page', {
          params: { courseId: id, page: 1, limit: 100 },
          headers
        });

        if (chapterRes.data.code !== 0) {
          this.$message.error('章节信息获取失败');
          return;
        }

        const chapters = chapterRes.data.data.list || [];

        // 对每个章节加载对应课时
        for (const chapter of chapters) {
          const lessonRes = await this.$http.get('lessons/page', {
            params: { chapterId: chapter.id, page: 1, limit: 100 },
            headers
          });
          const lessons = lessonRes.data.code === 0 ? lessonRes.data.data.list : [];
          chapter.lessons = lessons.map(lesson => ({
            id: lesson.id,
            title: lesson.title,
            lessonType: lesson.lessonType,
            videoUrl: lesson.videoUrl,
            pdfUrl: lesson.pdfUrl,
          }));
        }

        this.courseForm.chapters = chapters.map(chap => ({
          id: chap.id,
          title: chap.title,
          description: chap.description,
          lessons: chap.lessons
        }));

      } catch (error) {
        this.$message.error('加载课程详情失败');
        console.error(error);
      }
    },
    onDialogClosed() {
      this.addOrUpdateFlag = false;
      this.fetchCourseDetails(this.courseId);
    },
    onRefreshDataList() {
      this.addOrUpdateFlag = false;

      this.fetchCourseDetails(this.courseId);
    },

    handleCoverSuccess(response, file) {
      this.courseForm.coverUrl = URL.createObjectURL(file.raw);
      this.$message.success('封面上传成功');
    },

    beforeCoverUpload(file) {
      const isValid = ['image/jpeg', 'image/png'].includes(file.type);
      const isSmall = file.size / 1024 / 1024 < 2;
      if (!isValid) this.$message.error('只能上传 JPG/PNG 格式');
      if (!isSmall) this.$message.error('大小不能超过 2MB');
      return isValid && isSmall;
    },


    addOrUpdateLessonHandler(lessonId, chapterId) {
      this.lessonAddOrUpdateFlag = true;
      this.$nextTick(() => {
        this.$refs.lessonAddOrUpdate?.init(lessonId, chapterId);
      });
    },

    addOrUpdateChapterHandler(courseId, chapterId) {
      this.chapterAddOrUpdateFlag = true;
      this.$nextTick(() => {
        this.$refs.chapterAddOrUpdate?.init(courseId, chapterId);
      });
    },

       showGenerateDialog(chapterId,title) {
      this.currentChapterId = chapterId;
      this.currentChapterTitle = title;
      this.generateDialogVisible = true;
    },


    async generateAiFile(chapterId, type,title) {
      const token = localStorage.getItem('frontToken');
      if (!token) {
        this.$message.warning('请先登录！');
        this.$router.push('/login');
        return;
      }

       this.generating = true;
      //type为1生成docx，type为2生成pdf
      const requestData = {
        chapterId: chapterId,
        type: type
      };

      let apiUrl = '';
      let defaultFilenameExtension = '';
      let defaultContentType = '';

      if (type === 1) {
        defaultFilenameExtension = '.docx';
        defaultContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      } else if (type === 2) {
        defaultFilenameExtension = '.pdf';
        defaultContentType = 'application/pdf';
      } else {
        this.$message.error('不支持的文件类型。');
        return;
      }

      apiUrl= `api/ai/generateAiContentByChapter`;
      try {
        const response = await this.$http.post(
          apiUrl,
          requestData,
          {
            headers: {
              'Token': token,
              'Content-Type': 'application/json'
            },
            responseType: 'blob'
          }
        );

        if (response.status === 200 && response.data) {
          const contentDisposition = response.headers['content-disposition'];
          let filename = `Chapter_${title}_AIDocument${defaultFilenameExtension}`;

          if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
            if (filenameMatch && filenameMatch[1]) {
              filename = decodeURIComponent(filenameMatch[1]);
            }
          }

          const blob = new Blob([response.data], { type: response.headers['content-type'] || defaultContentType });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', filename);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          this.$message.success('文件下载成功！');

        } else {
          this.$message.error('文件生成或下载失败。');
          console.error('Response status:', response.status, 'Data:', response.data);
        }

      } catch (error) {
        this.$message.error('没有可用于AI生成的内容');
      } finally {
        this.generating = false; // 👈 结束加载
      }
    },
    onRefreshDataList() {
      this.getCourseDetail(this.courseId);
    },

    removeChapter(chatperId) {
      this.$confirm('确定要删除该章节吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
            url: `chapter/delete`,
            params: { id: chatperId },
            method: "post"
        }).then(res => {
          if (res.data.code === 0) {
            this.$message.success('章节删除成功');
            this.fetchCourseDetails(this.courseId);
          } else {
            this.$message.error(res.data.msg || '删除章节失败');
          }
        }).catch(() => {
          this.$message.error('删除章节失败，请稍后再试');
        });
      }).catch(() => {
        this.$message.info('已取消删除操作');
      });
    },

    removeLesson(lessonId) {

      this.$confirm('确定要删除该课时吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
            url: `lessons/delete`,
            params: { id: lessonId },
            method: "post"
        }).then(res => {
          if (res.data.code === 0) {
            this.$message.success('课时删除成功');
            this.fetchCourseDetails(this.courseId);
          } else {
            this.$message.error(res.data.msg || '删除课时失败');
          }
        }).catch(() => {
          this.$message.error('删除课时失败，请稍后再试');
        });
      }).catch(() => {
        this.$message.info('已取消删除操作');
      });
    },

    deleteVideoOrPdfUrl(lessonId, fileType, currentUrl) {
      this.$confirm(`确定要删除该${fileType === 'video' ? '视频' : 'PDF'}链接吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`lessons/deleteFile`, { params: { lessonId, fileType, currentUrl } })
          .then(res => {
            if (res.data.code === 0) {
              this.$message.success(`${fileType === 'video' ? '视频' : 'PDF'}链接删除成功`);
              this.getDataList();
            } else {
              this.$message.error(res.data.msg || `${fileType === 'video' ? '视频' : 'PDF'}链接删除失败`);
            }
          })
          .catch(() => {
            this.$message.error(`${fileType === 'video' ? '视频' : 'PDF'}链接删除失败，请稍后再试`);
          });
      }).catch(() => {
        this.$message.info('已取消删除操作');
      });
    },

    updateCourseInfo(courseId) {
      this.courseAddOrUpdateFlag = true;
      this.$nextTick(() => {
        this.$refs.courseAddOrUpdate?.init(courseId);
      });
    },

    previewVideo(videoUrl) {
      this.previewVideoUrl = videoUrl;
      this.previewVisible = true;
    },
   openFileUploadDialog(lessonId, fileType, currentUrl) {
  this.$refs.lessonUploadDialog.open(lessonId, fileType, currentUrl);
},


    onFileUploaded() {
      this.getDataList(); 
    },


    async showAiKnowledgeBase(lessonId) {
      const token = localStorage.getItem('frontToken');
      if (!token) {
        this.$message.warning('请先登录！');
        this.$router.push('/login');
        return;
      }

      try {
        const res = await this.$http.get(`lessons/getContentForAi`, 
        {
          headers: { 'Token': token },
          params: { lessonId:lessonId }
        }
      );

        if (res.data.code === 0 && res.data.data) {
          this.aiKnowledgeBaseContent = res.data.data;
          this.aiKnowledgeBaseVisible = true;
        } else if (res.data.code === 0 && !res.data.data) {
          this.$message.info('该课时暂无AI知识库内容。');
        }
        else {
          this.$message.error(res.data.msg || '获取AI知识库内容失败。');
          if (res.data.code === 401) {
            this.$message.error('登录失效，请重新登录。');
            // 可以触发一个登出流程
          }
        }
      } catch (error) {
        this.$message.error('请求AI知识库内容失败，请检查网络或稍后再试。');
        console.error('Fetch AI Knowledge Base error:', error);
      }
    },
  
    generateTestPaper(chapterId,title) {
      const token = localStorage.getItem('frontToken');
      if (!token) {
        this.$message.warning('请先登录！');
        this.$router.push('/login');
        return;
      }
        this.generating = true;
      this.$http.post(`api/ai/generateTestPaper`, { chapterId: chapterId }, {
        headers: { 'Token': token },
        responseType: 'blob'
      }).then(response => {
        if (response.status === 200 && response.data) {
          const contentDisposition = response.headers['content-disposition'];
          let filename = `Chapter_${title}_TestPaper.pdf`;

          if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
            if (filenameMatch && filenameMatch[1]) {
              filename = decodeURIComponent(filenameMatch[1]);
            }
          }

          const blob = new Blob([response.data], { type: 'application/pdf' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', filename);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          this.$message.success('试卷下载成功！');
        } else {
          this.$message.error('试卷生成或下载失败。');
        }
      }).catch(error => {
        this.$message.error('试卷生成失败，请稍后再试。');
        console.error('Generate test paper error:', error);
      }).finally(() => {
        this.generating = false; 
      });
    }

  },
  mounted() {
    if (this.courseId) {
      this.fetchCourseDetails(this.courseId);
    }
  },
  watch: {
    '$route.query.id'(newId) {
      this.courseId = newId;
      if (newId) {
        this.fetchCourseDetails(newId);
      } else {
        Object.assign(this.courseForm, {
          title: '',
          coverUrl: '',
          description: '',
          chapters: [],
        });
      }
    }
  }
};
</script>


<style scoped>
.course-form-container {
    max-width: 1200px; 
  margin: 0 auto;
  padding: 20px;
  background: #fff; 
}
.form-header {
  background-color: #fff;
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}
.form-main {
  padding: 20px;
}
.el-form {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h3 {
  margin-top: 30px;
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

h4 {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 16px;
  color: #666;
}

.right-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;

  .el-button {
    min-width: 100px;
  }
}
.chapter-card {
  margin-bottom: 20px;
}
.chapter-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chapter-card .card-header span {
  font-weight: bold;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
/* Element UI 的上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.button-group {
  display: flex; 
  gap: 10px;
  align-items: center;
}
.form-actions {
  margin-top: 30px;
  text-align: right;
}
</style>